package Practice8_JSON.P2;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.io.IOException;
import java.math.BigInteger;

public class Book {
    public String name;

    @JsonSerialize(using = IsbnSerializer.class)
    @JsonDeserialize(using = IsbnDeserializer.class)
    public BigInteger isbn;

    public Book(String name, BigInteger isbn) {
        this.name = name;
        this.isbn = isbn;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", isbn=" + isbn +
                '}';
    }
}

class IsbnDeserializer extends JsonDeserializer<BigInteger> {
    @Override
    public BigInteger deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException {
        String str = parser.getValueAsString();
        if (str != null) {
            try {
                return new BigInteger(str.replace("-", ""));
            } catch (NumberFormatException e) {
                throw new JsonParseException(parser, str, e);
            }
        }
        return null;
    }
}

class IsbnSerializer extends JsonSerializer<BigInteger> {

    @Override
    public void serialize(BigInteger bi, JsonGenerator gen, SerializerProvider prov) throws IOException {
        String str = bi.toString();
        str = String.format(str.substring(0, 3) + "-" + str.substring(3, 4) + "-" + str.substring(4, 7) + "-" + str.substring(7, 12) + "-" + str.substring(12, str.length()));
        gen.writeString(str);
    }
}
